import { Button, Divider, Space } from 'antd';
import { HomeOutlined, LogoutOutlined } from '@ant-design/icons';
import React from 'react';
import { useModel, SelectLang, history } from 'umi';
import Avatar from './AvatarDropdown';
import HeaderSearch from '../HeaderSearch';
import styles from './index.less';
import NoticeIconView from '../NoticeIcon';
import { logout } from '@/services';
import { stringify } from 'querystring';

export type SiderTheme = 'light' | 'dark';

const GlobalHeaderRight: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};

  if (!initialState || !initialState.settings) {
    return null;
  }

  /**
   * 返回主页
   */
  const goHome = () => {
    history.push('/');
  }


  /**
   * 退出登录，并且将当前的 url 保存
   */
  const loginOut = async () => {
    await logout();
    const { query = {}, pathname } = history.location;
    const { redirect } = query;
    // Note: There may be security issues, please note
    if (window.location.pathname !== '/user/login' && !redirect) {
      history.replace({
        pathname: '/user/login',
        search: stringify({
          redirect: pathname,
        }),
      });
    }
  };

  const { navTheme, layout } = initialState.settings;
  let className = styles.right;

  if ((navTheme === 'dark' && layout === 'top') || layout === 'mix') {
    className = `${styles.right}  ${styles.dark}`;
  }

  return (
    <Space className={className}>
      <HeaderSearch
        className={`${styles.action} ${styles.search}`}
        placeholder="站内搜索"
        // defaultValue="JSON工具"
        options={[
          {
            label: <a href="/jsonstring/format">JSON格式化</a>,
            value: 'JSON格式化',
          },
          {
            label: <a href="/jsonstring/compare">对比工具</a>,
            value: '对比工具',
          },
        ]} // onSearch={value => {
        //   console.log('input', value);
        // }}
      />
      <NoticeIconView />
      <HomeOutlined className={styles.action} style={{ paddingTop: '4px'}} onClick={goHome}/>
      <Divider type="vertical" />
      {currentUser?.userName === 'anon' ? (
        // 这里不能简单跳转哦，因为匿名用户也是一种用户的登陆形式，要登出
        <Button onClick={loginOut}>
          <LogoutOutlined />
          登录
        </Button>
      ) : (
        <Avatar />
      )}
      <SelectLang className={styles.action} />
    </Space>
  );
};

export default GlobalHeaderRight;
